import React, { useState, useEffect } from 'react'
import type { ComplianceItem } from '@/types/work'
import type { Attachment } from '@/types/work'
import type { ProgressStatus } from '@/types/work'
import type { CheckItemTemplate } from '@/types/template'
import ComplianceFormFields from './ComplianceFormFields'
import FileUploadSection from './FileUploadSection'
import FileRenameModal from './FileRenameModal'
import StatusSelectionDialog from './StatusSelectionDialog'
import { useBusiness } from '@/stores/useBusinessStore'
import { useComplianceStore } from '@/stores/useComplianceStore'
import { templateApi } from '@/api/template'
import { showMessage } from '@/components/common/MessageTip'

interface ComplianceFormProps {
  mode: 'create' | 'edit'
  initialData: ComplianceItem
  onClose: () => void
  onSubmit: (item: Partial<ComplianceItem>, callback?: (saved: ComplianceItem) => void) => void
}

const ComplianceForm: React.FC<ComplianceFormProps> = ({
  mode,
  initialData,
  onClose,
  onSubmit
}) => {
  // 获取业务系统信息
  const { selectedBusiness } = useBusiness()
  const isDataSecurityAssessment = selectedBusiness?.assessmentType === '105'
  
  // 获取 store 方法
  const { updateItemAttachments } = useComplianceStore()
  
  // 初始化表单数据
  const [formData, setFormData] = useState<ComplianceItem>(() => {
      return { ...initialData }
  })
  
  // 表单验证错误
  const [errors, setErrors] = useState<Record<string, string>>({})
  
  // 状态选择对话框
  const [showStatusDialog, setShowStatusDialog] = useState(false)
  const [tempFormData, setTempFormData] = useState<Partial<ComplianceItem>>({})
  
  // 文件重命名状态
  const [renamingFile, setRenamingFile] = useState<File | null>(null)
  const [renamedFileToUpload, setRenamedFileToUpload] = useState<File | null>(null)
  
  // 数据安全评估相关状态
  const [templateItems, setTemplateItems] = useState<CheckItemTemplate[]>([])
  const [currentMaturityLevel, setCurrentMaturityLevel] = useState<number>(
    initialData?.maturity_level || 1
  )
  const [isLoadingTemplateItems, setIsLoadingTemplateItems] = useState(false)
  
  // 处理表单字段变更
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
    
    // 清除该字段的错误
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev }
        delete newErrors[name]
        return newErrors
      })
    }
  }
  
  // 处理附件变更（统一更新表单和全局 store）
  const handleAttachmentsChange = (newAttachments: Attachment[]) => {
    console.log('newAttachments', newAttachments)
    
    // 更新表单数据
    setFormData(prev => ({
      ...prev,
      attachments: newAttachments
    }))
    
    // 同时更新全局 store（这样 ComplianceCard 也能立即看到变化）
    if (formData.id) {
      updateItemAttachments(formData.id, newAttachments)
    }
  }

  // 处理文件重命名
  const handleFileRename = (file: File) => {
    setRenamingFile(file)
  }

  // 重命名确认 - 设置重命名文件供 FileUploadSection 处理
  const handleRenameConfirm = (renamedFile: File) => {
    setRenamingFile(null)
    setRenamedFileToUpload(renamedFile)
  }

  // 重命名文件上传完成回调
  const handleRenamedFileUploaded = () => {
    setRenamedFileToUpload(null)
  }

  // 重命名取消
  const handleRenameCancel = () => {
    setRenamingFile(null)
  }

  // 加载模板项（仅在数据安全评估且编辑模式下）
  useEffect(() => {
    const loadTemplateItems = async () => {
      if (!isDataSecurityAssessment || mode !== 'edit' || !initialData?.title || !selectedBusiness?.id) {
        return
      }

      setIsLoadingTemplateItems(true)
      try {
        const items = await templateApi.getTemplateItemsByAssessmentPlan(
          selectedBusiness.id,
          initialData.title
        )
        
        // 按成熟度等级排序
        const sortedItems = items.sort((a, b) => 
          (a.maturity_level || 1) - (b.maturity_level || 1)
        )
        
        setTemplateItems(sortedItems)
      } catch (error) {
        console.error('加载模板项失败:', error)
        showMessage('error', '加载模板项失败')
      } finally {
        setIsLoadingTemplateItems(false)
      }
    }

    loadTemplateItems()
  }, [isDataSecurityAssessment, mode, initialData?.title, selectedBusiness?.id])

  // 成熟度等级切换处理
  const handleMaturityLevelChange = (level: number) => {
    // 检查该等级是否有对应的模板内容
    const targetItem = templateItems.find(item => item.maturity_level === level)
    
    if (!targetItem) {
      showMessage('warning', `成熟度等级 ${level} 暂无模板内容，无法选择`)
      return
    }
    
    setCurrentMaturityLevel(level)
    setFormData(prev => ({
      ...prev,
      description: targetItem.description,
      guide: targetItem.guide,
      maturity_level: level
    }))
  }

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {}
    if (!formData.inspector?.trim()) {
      newErrors.inspector = '检查描述不能为空'
    }
    
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors)
      return false
    }
    
    return true
  }
  
  // 表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    
    if (validateForm()) {
      // 如果表单验证通过，显示状态选择对话框
      setTempFormData({...formData})
      setShowStatusDialog(true)
    }
  }
  
  // 提交带状态的表单
  const handleStatusSubmit = (status: ProgressStatus) => {
    const finalData = {
      ...tempFormData,
      progress_status: status
    }
    onSubmit(finalData as ComplianceItem)
    setShowStatusDialog(false)
  }

  // 关闭状态选择对话框
  const handleStatusClose = () => {
    setShowStatusDialog(false)
  }

  // 阻止点击模态框内容时关闭模态框
  const handleModalContentClick = (e: React.MouseEvent) => {
    e.stopPropagation()
  }

  return (
    <div 
      className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
    >
      {/* 文件重命名模态框 */}
      <FileRenameModal
        file={renamingFile}
        isOpen={!!renamingFile}
        onClose={handleRenameCancel}
        onConfirm={handleRenameConfirm}
      />
      
      <div 
        className="bg-card text-card-foreground rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto"
        onClick={handleModalContentClick}
      >
        <div className="p-6">
          <h2 className="text-2xl font-semibold text-foreground mb-6">
            {mode === 'create' ? '添加检查项' : '编辑检查项'}
          </h2>
          
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* 基本信息表单字段 */}
            <ComplianceFormFields
              formData={formData}
              errors={errors}
              mode={mode}
              onChange={handleChange}
              isDataSecurityAssessment={isDataSecurityAssessment}
              currentMaturityLevel={currentMaturityLevel}
              onMaturityLevelChange={handleMaturityLevelChange}
              isLoadingTemplateItems={isLoadingTemplateItems}
              templateItems={templateItems}
              assessmentType={selectedBusiness?.assessmentType}
            />
            
            {/* 文件上传区域 */}
            <FileUploadSection
              attachments={formData.attachments || []}
              onAttachmentsChange={handleAttachmentsChange}
              onFileRename={handleFileRename}
              complianceItemId={formData.id}
              renamedFileToUpload={renamedFileToUpload}
              onRenamedFileUploaded={handleRenamedFileUploaded}
              assessmentPlanId={selectedBusiness?.id}
            />
            
            {/* 表单按钮 */}
            <div className="flex justify-end space-x-3 pt-4 border-t border-border">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 bg-secondary text-secondary-foreground rounded-md transition-colors"
              >
                取消
              </button>
              <button
                type="submit"
                className="px-4 py-2 bg-primary text-primary-foreground rounded-md transition-colors"
              >
                {mode === 'create' ? '添加' : '保存'}
              </button>
            </div>
          </form>
        </div>
      </div>
      
      {/* 状态选择对话框 */}
      <StatusSelectionDialog
        isOpen={showStatusDialog}
        onClose={handleStatusClose}
        onSubmit={handleStatusSubmit}
      />
    </div>
  )
}

export default ComplianceForm
